// 赵杨   登录    动态路由菜单列表

var express = require('express');
var router = express.Router();
const db = require('../../db/db');
// 用这个包来生成 Token 字符串
const jwt = require('jsonwebtoken')


// 验证吗
const svgCaptcha = require('svg-captcha');

// 导入秘钥
const config = require('../../config')

let text = ''

// 获取验证码接口
router.get('/captcha', function (req, res) {
  // 生成普通验证码图片
  text = ''
  const captcha = svgCaptcha.create({
    size: 4, // 验证码长度
    noise: 3, // 干扰线数量
    fontSize: 50, // 字体大小
    width: 150, // 图片宽度
    height: 50, // 图片高度
    color: true, // 随机颜色
    background: '#f5f5f5' // 背景颜色
  });

  // console.log("验证码信息",captcha.text)
 // **重要：将验证码文本存储到 session 中**
  req.session.captchaText = captcha.text;
  text = captcha.text
  res.cc(200, '验证码获取成功', {captchaImg: captcha.data})
  
});

// 登录接口
router.post('/login', function (req, res, next) { 
  const { username, password, captcha } = req.body;
  
  if (!username || !password || !captcha) { // 检查验证码是否也为空
   text = ''
   return res.cc(0, "用户名、密码或验证码不能为空");
   
  }
    const sql = `select * from sys_systemset where F_AdminAccount = ?`;
  db.query(sql,  username, (err, result) => { 
    if (err) {
      text = ''
      return res.cc(0, '登录失败');
    } 
    if (result.length !== 1) {
      text = ''
      return res.cc(0, '登录失败');
    }
    if (result[0].F_AdminPassword !== password) {
     text = ''
      return res.cc(0, '账号或密码错误');
    }
  // // **1. 验证码校验**
    // const storedCaptchaText = req.session.captchaText;
    const storedCaptchaText = text;
    

  // // **重要：清除 session 中的验证码，无论校验成功或失败**
  delete req.session.captchaText;

  // 进行验证码比对（通常不区分大小写）
    if (!storedCaptchaText || captcha.toLowerCase() !== storedCaptchaText.toLowerCase()) {
    text = ''
    return res.cc(0, '验证码错误');
  }

    // 生成token字符串
    
    // 把敏感信息去除
    const user = { ...result[0], F_AdminPassword: '' }
    const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: config.expiresIn })
    const data = {id:result[0].F_CreatorUserId, token: 'Bearer ' + tokenStr }
    res.cc(200, '登录成功', data)
   text = ''
   })
});


// 查询个人信息
router.get('/userinfo', function (req, res, next) { 

  const sql = `select * from sys_user where F_Id = ?`;
  db.query(sql, req.auth.F_CreatorUserId, (err, result) => { 
    if (err) return res.cc(0, '查询失败');
    if (result.length !== 1) return res.cc(0, '查询失败');
    const userData = {
      username: result[0].F_Account,
      name: result[0].F_ReaName,
      gender: result[0].F_Gender,
      age: result[0].F_Birthday,
      phone: result[0].F_MobilePhone,
      email: result[0].F_Email,
      description: result[0].F_Description
    }
    res.cc(200, '查询成功', userData)
  })

})


// 修改个人信息
router.post('/updateInfo', function (req, res, next) {

  const sql = `update sys_user set F_Account = ?, F_RealName = ?, F_Gender = ?, F_Birthday = ?, F_MobilePhone = ?, F_Email = ?, F_Description = ? where F_Id = ?`;
  db.query(sql, [req.body.username, req.body.name, req.body.gender, req.body.age, req.body.phone, req.body.email, req.body.description, req.auth.F_CreatorUserId], (err, result) => {
    if (err) return res.cc(0, err);
    if (result.affectedRows !== 1) return res.cc(0, '修改失败');
    res.cc(200, '修改成功')
  })
})


// 修改密码
router.post('/updatePwd', function (req, res, next) { 
  if (!req.body.password) return res.cc(0, '密码不能为空');
  if (req.body.password !== req.body.repassword) return res.cc(0, '两次密码不一致');
  const sql = `update sys_systemset set F_AdminPassword = ? where F_CreatorUserId = ?`;
  db.query(sql, ['0000', req.auth.F_CreatorUserId], (err, result) => { 
    if (err) return res.cc(0, err);
    if (result.affectedRows !== 1) return res.cc(0, '修改失败');
    res.cc(200, '修改成功')
  })
})


// 动态路由菜单列表
router.get('/menuList', function (req, res, next) {
  const sql = `select F_FullName,F_Icon,F_UrlAddress,F_SortCode,F_Target,F_IsMenu,F_IsExpand,F_IsPublic,F_IsFields,F_EnabledMark,F_Authorize,F_CreatorTime,F_Description from sys_module`;
  db.query(sql, (err, result) => { 
    if (err) return res.cc(0, err);
    res.cc(200, '查询成功', result)
  })
})








module.exports = router;
